package com.buvaka;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

import com.buvaka.features.Features;


public class UpdateLinestylesFile {
	static final String VAR_LINESTYLES = "var lineStyles = ";
	public static void update (MongoClient client) {
		try (FileOutputStream fout = new FileOutputStream( "src/main/webapp/js/lineStyles.js" )){
			MongoClient mongo = client;
            DB db = mongo.getDB("gis");
            DBCollection styles = db.getCollection("lineStyles");
            DBCursor allStyles = styles.find();
            FileChannel fc2 = fout.getChannel();
                
            StringBuilder str = new StringBuilder(VAR_LINESTYLES).append(Features.OPEN);
            
            while (allStyles.hasNext()) {
            	DBObject current = allStyles.next();
            	str.append(current.get("_id"));
            	current.removeField("_id");
            	str.append(":");
            	str.append(current.toString()).append(Features.COMMA);
            }
            
            str.setLength(str.length() - 2); //remove comma + space at the end
            
            str.append(Features.CLOSE).append(";");
            fc2.write(ByteBuffer.wrap(str.toString().getBytes("UTF-8")));            
            
            
		} catch (IOException e) {
            e.printStackTrace();
        }

	}
	
	public static void main (String args[]) throws Exception{
		update(new MongoClient());
	}
	
}